<template>
  <el-form
    ref="ruleFormRef"
    :model="newFormInline"
    :rules="formRules"
    label-width="100px"
    class="w-full"
  >
    <el-form-item label="上级区域" prop="parentZoneId">
      <el-cascader
        v-model="newFormInline.parentZoneId"
        class="w-full"
        :options="parentOptions"
        :props="cascaderProps"
        placeholder="请选择上级区域"
        clearable
        :disabled="title !== '创建'"
      />
    </el-form-item>
    <el-form-item label="分区名称" prop="name">
      <el-input v-model="newFormInline.name" placeholder="请输入分区名称" />
    </el-form-item>
    <el-form-item label="备注" prop="comment">
      <el-input
        v-model="newFormInline.comment"
        type="textarea"
        :maxlength="200"
        show-word-limit
        :rows="4"
        placeholder="请输入备注，最多200字"
      />
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, defineProps } from "vue";
import { PartitionFormProps } from "../componentsUtils/type/partitionTypes";
import {
  formRules,
  setOriginalFormId
} from "../componentsUtils/rule/partitionRules";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import { handleTree } from "@/utils/tree";
import { PureTable } from "@pureadmin/table";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Delete from "~icons/ep/delete";
import EditPen from "~icons/ep/edit-pen";
import Refresh from "~icons/ep/refresh";
import AddFill from "~icons/ri/add-circle-line";
import { usePartitionTable } from "../componentsUtils/usePartitionTable";

const props = withDefaults(defineProps<PartitionFormProps>(), {
  formInline: () => ({
    id: 0,
    name: "",
    dealerId: 0,
    dealerName: "",
    tenantId: 0,
    tenantName: "",
    comment: "",
    parentZoneId: 0,
    level: 1
  }),
  title: ""
});
const newFormInline = ref(props.formInline);
const ruleFormRef = ref();
const parentOptions = ref<any[]>([]);
const loading = ref(false);

// 级联选择器属性配置
const cascaderProps = {
  value: "Id",
  label: "Name",
  children: "children",
  emitPath: false, // 只返回最后一级的ID
  checkStrictly: true // 允许选择任意一级
};

// 监听props.form的变化，同步到localForm
watch(
  () => props.formInline,
  newValue => {
    newFormInline.value = { ...newValue };
    // 如果是编辑模式，自动计算等级
    if (newValue.parentZoneId) {
      calculateLevel(newValue.parentZoneId);
    }
  },
  { deep: true }
);

// 监听上级区域变化，自动计算等级
watch(
  () => newFormInline.value.parentZoneId,
  newParentZoneId => {
    if (newParentZoneId) {
      calculateLevel(newParentZoneId);
    } else {
      newFormInline.value.level = 1; // 如果没有上级区域，默认为第一级
    }
  }
);

// 计算等级的方法
function calculateLevel(parentZoneId: number) {
  // 查找上级区域的等级，然后+1
  const findLevel = (nodes: any[], id: number): number => {
    for (const node of nodes) {
      if (node.Id === id) {
        return (node.Level || 1) + 1;
      }
      if (node.children && node.children.length > 0) {
        const level = findLevel(node.children, id);
        if (level > 1) {
          return level;
        }
      }
    }
    return 2; // 如果上级区域不存在，默认为2级
  };

  // 确保parentOptions有值
  if (parentOptions.value && parentOptions.value.length > 0) {
    newFormInline.value.level = findLevel(parentOptions.value, parentZoneId);
  } else {
    newFormInline.value.level = 2; // 默认为2级
  }
}

function getParentOptions(): Promise<void> {
  return new Promise(resolve => {
    loading.value = true;
    http
      .get(changeHttpLink("/api/Zone/select"), {
        params: {
          tenantId: props.formInline.tenantId,
          excludedId: props.formInline.id // 排除当前编辑的区域，避免自引用
        }
      })
      .then((res: any) => {
        loading.value = false;
        if (res.Success) {
          // 转换为树形结构
          parentOptions.value = handleTree(
            res.Data || [],
            "Id",
            "ParentZoneId",
            "children"
          );
        }
        resolve();
      })
      .catch(err => {
        loading.value = false;
        console.error("获取上级区域列表失败:", err);
        resolve();
      });
  });
}

// 添加获取表单数据的方法
function getFormData() {
  return newFormInline.value;
}

function getRef() {
  return ruleFormRef.value;
}

onMounted(() => {
  setOriginalFormId(props.formInline.id || 0);
  // 获取上级区域列表
  getParentOptions().then(() => {
    // 数据加载完成后再计算等级
    if (props.formInline.parentZoneId) {
      calculateLevel(props.formInline.parentZoneId);
    }
  });
});

defineExpose({ getRef, getFormData });
</script>
